package swing.frame;

import api.UserApi;
import beanInfo.UserInfo;
import client.UserSession;
import swing.BaseFrame;
import swing.FrameManager;
import http.Response;
import model.ApiResultModel;
import model.UserLoginInfoModel;
import myException.InputFormatException;
import myException.ServerConnectException;
import swing.dialog.RegisterDialog;
import swing.customComp.HintJPasswordField;
import swing.customComp.HintJTextField;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;

/**
 * 登录界面
 */
public class LoginFrame extends BaseFrame {

    public final static String frameTitle = "开源词典";

    //登录界面组件容器
    public JPanel loginPanel;

    private HintJTextField accountTextField;
    private HintJPasswordField passwordField;

    private JButton loginButton;
    private JButton registerButton;

    private ActionListener loginActionListener;


//组件初始化代码
//----------------------------------------------------------------------------------------------------------------------
    @Override
    protected void initFrame() {
        this.setTitle(frameTitle);
        loginPanel = new JPanel();
        loginPanel.setLayout(null);
        this.setContentPane(loginPanel);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setPreferredSize(new Dimension(400, 300));
        this.setResizable(false);
        this.pack();
        //让窗口位于屏幕正中间，要放在pack()后才能生效
        this.setLocationRelativeTo(null);
    }

    @Override
    protected void initAllComponent() {
        //账户输入框
        accountTextField = new HintJTextField();
        accountTextField.setBounds(30, 35, 285, 35);
        accountTextField.setHintText("账户");
        //密码输入框
        passwordField = new HintJPasswordField();
        passwordField.setBounds(30, 90, 285, 35);
        passwordField.setEchoChar((char)0);
        passwordField.setHintText("登录密码");
        //登录按钮
        loginButton = new JButton("登录");
        loginButton.setBounds(30, 155, 110, 35);
        loginActionListener = listen -> {
            String account = accountTextField.getText().trim();
            String pwd = passwordField.getText().trim();
            new Thread(() -> {
                login(account, pwd);
            }).start();
        };
        loginButton.addActionListener(loginActionListener);
        SwingUtilities.invokeLater(() -> loginButton.requestFocusInWindow());
        //注册按钮
        registerButton = new JButton("注册");
        registerButton.setBounds(205, 155, 110, 35);
        registerButton.addActionListener(listen -> {
            RegisterDialog registerDialog = new RegisterDialog(this);
            registerDialog.setVisible(true);
        });
    }

    @Override
    protected void addAllComponent() {
        loginPanel.add(accountTextField);
        loginPanel.add(passwordField);
        loginPanel.add(loginButton);
        loginPanel.add(registerButton);
    }
//----------------------------------------------------------------------------------------------------------------------


//组件状态更新代码
//----------------------------------------------------------------------------------------------------------------------
    private void enterLoginState() {
        loginButton.setText("登录中...");
        loginButton.removeActionListener(loginActionListener);
        accountTextField.setEnabled(false);
        passwordField.setEnabled(false);
    }

    private void exitLoginState() {
        loginButton.setText("登录");
        loginButton.addActionListener(loginActionListener);
        accountTextField.setEnabled(true);
        passwordField.setEnabled(true);
    }
//----------------------------------------------------------------------------------------------------------------------


//事件响应方法代码
//----------------------------------------------------------------------------------------------------------------------

    public void login(String account, String pwd) {
        if (account.isEmpty() || pwd.isEmpty()) {
            showMessageDialog("请输入账户和密码进行登录");
            return;
        }
        if (!UserInfo.isAccountAndPwdLengthLegal(account, pwd)) {
            showMessageDialog("用户名或密码长度不合法！");
            return;
        }
        try {
            SwingUtilities.invokeLater(this::enterLoginState);
            Response response = UserApi.login(account, pwd);
            if (response.getStatus_code() != Response.OK) {
                showMessageDialog(response.getStatus_code() + " " + response.getStatus_description());
                return;
            }
            ApiResultModel<UserLoginInfoModel> apiResult = ApiResultModel.fromJson(response.getBody(), UserLoginInfoModel.class);
            if (apiResult.getCode() == ApiResultModel.FAIL_CODE) {
                showMessageDialog(apiResult.getMessage());
                return;
            }
            UserLoginInfoModel userLoginInfo = apiResult.getResult();
            //保存用户登录信息
            UserSession.initLoginSession(userLoginInfo);
            //登录成功后启动程序主界面并关闭登录界面
            FrameManager.showMainFrame();
            JFrame jFrame = (JFrame)SwingUtilities.getRoot(loginPanel);
            jFrame.dispose();
        } catch (ServerConnectException e) {
            showMessageDialog("服务器连接失败！");
            e.printStackTrace();
        } catch (InputFormatException e) {
            showMessageDialog("数据格式错误！");
            e.printStackTrace();
        } finally {
            SwingUtilities.invokeLater(this::exitLoginState);
        }
    }

}
